package com.cslg.yougou.front.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cslg.yougou.front.entity.YougouMember;
import com.cslg.yougou.front.mapper.YougouMemberMapper;
import com.cslg.yougou.front.pojo.LoginPojo;
import com.cslg.yougou.front.pojo.Result;
import com.cslg.yougou.front.service.YougouMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cslg.yougou.utils.AesCbcUtil;
import com.cslg.yougou.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyw
 * @since 2020-11-04
 */
//开启事务
@Transactional
@Service
public class YougouMemberServiceImpl  extends ServiceImpl<YougouMemberMapper, YougouMember> implements YougouMemberService {

    @Value("${wxconfig.appid}")
    String appid;
    @Value("${wxconfig.secret}")
    String secret;
    @Override
    public Result login(String code, String encryptedData, String iv, HttpServletRequest request) {
        YougouMember yougouMember = null;
        LoginPojo loginPojo = new LoginPojo();
        String openid = "";
        String sessionKey = "";
        JSONObject sessionKeyOrOpenId = WechatUtil.getSessionKeyOrOpenId(code,appid,secret);
        //获取openid
        System.out.println(sessionKeyOrOpenId);
        if(!sessionKeyOrOpenId.containsKey("openid")){

            return Result.errorMsg("获取用户失败");
        }
        openid = sessionKeyOrOpenId.getString("openid");
        sessionKey = sessionKeyOrOpenId.getString("session_key");
        //查询用户是否存在
        QueryWrapper<YougouMember> yougouMemberQueryWrapper = new QueryWrapper<>();
        yougouMemberQueryWrapper.lambda().eq(YougouMember::getOpenid,openid);
        List<YougouMember> yougouMembers = list(yougouMemberQueryWrapper);

        //不存在先解密用户数据
        if(yougouMembers==null||yougouMembers.size()==0){
            try {
                yougouMember = deCodeUserInfo(encryptedData,sessionKey,iv,"utf-8");
                this.baseMapper.insert(yougouMember);
            }catch (Exception e){
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  Result.errorMsg("解密用户密钥失败");
            }
        }else{
            yougouMember = yougouMembers.get(0);
        }
        //返回用户数据
        loginPojo.setAvatar(yougouMember.getAvatar());
        loginPojo.setCurrentTime(LocalDateTime.now());
        loginPojo.setNickname(yougouMember.getNickname());
        loginPojo.setToken(DigestUtils.md5DigestAsHex((yougouMember.getOpenid()).getBytes()));
        return Result.ok(loginPojo);
    }

    @Override
    public YougouMember deCodeUserInfo(String encryptedData, String session_key, String iv, String charset) throws Exception {
        String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, charset);
        if (null != result && result.length() > 0) {
            JSONObject userInfoJSON = JSONObject.parseObject(result);
            YougouMember yougouMember = new YougouMember();
            yougouMember.setAvatar(userInfoJSON.getString("avatarUrl"));
            yougouMember.setNickname(userInfoJSON.getString("nickName"));
            yougouMember.setOpenid(userInfoJSON.getString("openId"));
            return yougouMember;
        }
        return null;
    }


}
